package org.changs.record.home;

import org.changs.aplug.base.BasePresenter;
import org.changs.media.MediaFile;
import org.changs.media.MediaManager;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yincs on 2017/9/5.
 */

public class MainPresenter extends BasePresenter<MainContract.V> implements MainContract.P, MediaManager.Callback {

    private final MediaManager mMediaManager;

    @Inject
    public MainPresenter(MediaManager mediaManager) {
        this.mMediaManager = mediaManager;
    }

    @Override
    public void attachView(MainContract.V v) {
        super.attachView(v);
        mMediaManager.registerCallback(this);
        load();
    }

    @Override
    public void detachView() {
        super.detachView();
        mMediaManager.unregisterCallback(this);
    }

    @Override
    public void load() {
        if (mMediaManager.getMedia().size() == 0) {
            if (isAttachView())
                getMvpView().showLoading().setMessage("正在加载本地数据");
            mMediaManager.reload();
        } else {
            if (isAttachView()) {
                getMvpView().afterLoadMedia();
            }
        }
    }

    @Override
    public void delete(MediaFile mediaFile) {

    }

    @Override
    public void reload() {
        if (isAttachView()) {
            getMvpView().afterLoadMedia();
            Observable.timer(1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(ignore -> {
                        if (isAttachView()) getMvpView().hideLoading();
                    });
        }
    }

    @Override
    public void upload(MediaFile mediaFile) {

    }
}
